package com.ray.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TimeTest {

    public static void main(String[] args) {
        final TimeLock timeLock = new TimeLock();
        new Thread(new Runnable() {
            public void run() {

                timeLock.getLock();
            }
        },"A").start();

        new Thread(new Runnable() {
            public void run() {
                timeLock.getLock();
            }
        },"B").start();
    }
}

class TimeLock {

    private ReentrantLock lock = new ReentrantLock();

    public void getLock(){
        try {
            if(lock.tryLock(3, TimeUnit.SECONDS )){
                System.out.println(Thread.currentThread().getName()+"拿到了锁");
                TimeUnit.SECONDS.sleep(5);
            }else{
                System.out.println(Thread.currentThread().getName()+"没有拿到锁");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            if(lock.isHeldByCurrentThread()){
                lock.unlock();
            }

        }
    }
}

